package com.ccrfid.rmc6.service.mattress;

import com.ccrfid.rmc6.pojo.dto.mattress.MattressMsgDto;
import com.ccrfid.rmc6.util.CRC8Util;
import com.ccrfid.rmc6.util.JsonUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.eventbus.EventBus;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.msgpack.jackson.dataformat.MessagePackFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class MattressDataHandler extends ByteToMessageDecoder {
    private static final Logger logger = LoggerFactory.getLogger(MattressDataHandler.class);

    private EventBus eventBus;

    public MattressDataHandler(EventBus eventBus) {
        this.eventBus = eventBus;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        byte[] buf = new byte[in.capacity()];
        in.readBytes(buf);
        if (logger.isTraceEnabled()) {
            logger.trace("mattress raw data: {}", getBufString(buf));
        }

        int crc = buf[1] & 0xFF;
        int calcCrc8 = CRC8Util.calcCRC8(buf, 2, buf.length - 2) & 0xFF;
        if (calcCrc8 == crc) {
            ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory());
            MattressMsgDto mattressMsg = objectMapper.readValue(buf, 2, buf.length - 2, MattressMsgDto.class);
            //post msg
            eventBus.post(mattressMsg);
            if (logger.isTraceEnabled()) {
                logger.trace("mattress data: {}", JsonUtil.INSTANCE.writeValueAsString(mattressMsg));
            }
        } else {
            logger.debug("crc:calcCrc failed! {}:{}", crc, calcCrc8);
        }
    }

    private String getBufString(byte[] buf) {
        String str = "";
        for (byte b : buf) {
            str += String.format("%02x", b);
        }
        return str;
    }

}
